package com.changgou.service.impl;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.goods.feign.CategoryFeign;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.service.PageService;

/**
 * 静态页生成逻辑
 * 
 * @author gaofeng
 * @date 2025年04月28日 16:50
 */
@Service("pageServiceImpl")
public class PageServiceImpl implements PageService {
    @Resource
    private SpuFeign spuFeign;

    @Resource
    private CategoryFeign categoryFeign;

    @Resource
    private SkuFeign skuFeign;

    @Resource
    private TemplateEngine templateEngine;

    // 生成静态文件路径
    @Value("${pagePath}")
    private String pagePath;

    @Override
    public void createPageHtml(Long spuId) {
        // 1、上下文
        Context context = new Context();
        context.setVariables(buildDataModel(spuId));

        // 2、准备条件
        File dir = new File(pagePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File dest = new File(dir, spuId + ".html");
        try (PrintWriter writer = new PrintWriter(dest, "UTF-8")) {
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String, Object> buildDataModel(Long spuId) {
        Map<String, Object> dataMap = new HashMap<>();

        Result<Spu> spuResult = spuFeign.findById(spuId);
        Spu spu = spuResult.getData();

        dataMap.put("category1", categoryFeign.findById(spu.getCategory1Id()).getData());
        dataMap.put("category2", categoryFeign.findById(spu.getCategory2Id()).getData());
        dataMap.put("category3", categoryFeign.findById(spu.getCategory3Id()).getData());

        String spuImages = spu.getImages();
        if (StringUtils.isNotBlank(spuImages)) {
            dataMap.put("imageList", spuImages.split(","));
        }

        dataMap.put("specificationList", JSON.parseObject(spu.getSpecItems(), Map.class));
        dataMap.put("spu", spu);

        Sku sku = new Sku();
        sku.setSpuId(spuId);
        Result<List<Sku>> skuResult = skuFeign.findList(sku);
        dataMap.put("skuList", skuResult.getData());
        return dataMap;
    }
}
